import React, { useState, useEffect, useRef, useImperativeHandle, forwardRef } from 'react';
import { Button, Table, Select, Input, message } from 'antd';
import Modal from '../../../../../../components/Modal';
import { TYPE_OPTIONS } from '../../../../../../utils/constant';
import { randomKey } from '../../../../../../utils/utils';
import CodeMap from './codeMap';
import MapResult from './mapResult';
const x2js = require('x2js');

const SetUp = forwardRef((props, ref) => {
  const { value, curFaceId } = props;

  const [data, setData] = useState([]);
  const [isParse, setIsParse] = useState(false);
  const codeMapRef = useRef();

  useImperativeHandle(ref, () => ({
    getData: () => data,
  }));

  useEffect(() => {
    if (value.returningMaps) {
      const tempReturningmaps = value.returningMaps.map((item) => ({ ...item, frontId: randomKey() }));
      setData(tempReturningmaps);
    }
  }, [value.returningMaps]);

  useEffect(() => {
    if (curFaceId) {
      setData([])
    }
  }, [curFaceId]);

  const handleParse = () => {
    if (isParse && data.length) {
      Modal.open({
        title: '提示',
        width: '300px',
        content: <div style={{ marginBottom: '20px' }}>已有映射数据，是否覆盖?</div>,
        ok: () => {
          Modal.close();
          getInitData();
        },
      });
    } else {
      getInitData();
    }
  };

  // 设置映射
  const getInitData = () => {
    const { tpSuccessExample, tpReturningType } = value;
    if (!tpSuccessExample) return message.warning('请选择数据源！');
    let mapObj = {};
    if (tpReturningType) {
      const x2json = new x2js();
      mapObj = x2json.xml2js(tpSuccessExample);
    } else {
      mapObj = JSON.parse(tpSuccessExample);
    }
    const mapData = getFormatData(mapObj);
    if (!mapData.length) return message.warning('没有可解析的内容！');
    const data = mapData.map((item) => ({
      frontId: randomKey(),
      thirdPath: item,
      innerPath: item,
      type: 0,
      isReturning: 1,
    }));
    setData(data);
    if (!isParse) message.success('解析成功！');
    setIsParse(true);
  };

  const getFormatData = (data) => {
    let result = [];
    const transformData = (obj, pKey, type) => {
      Object.keys(obj).forEach((key) => {
        const new_key = pKey ? (type ? `${pKey}[]` : `${pKey}.${key}`) : key;
        if (Object.prototype.toString.call(obj[key]) === '[object Object]') {
          transformData(obj[key], new_key);
        } else if (
          Object.prototype.toString.call(obj[key]) === '[object Array]' &&
          obj[key].every((item) => typeof item === 'object')
        ) {
          transformData(obj[key], new_key, 1);
        } else {
          result.push(new_key);
        }
      });
    };
    transformData(data);
    return Array.from(new Set(result));
  };

  const handleAdd = () => {
    const temp = [...data];
    temp.push({ thirdPath: '', innerPath: '', type: 0, isReturning: 1, isNew: true, frontId: randomKey() });
    setData(temp);
  };

  const handleReview = () => {
    const newMap = data.map((item) => item.innerPath);
    const resultObj = getFormatObject(newMap);
    Modal.open({
      title: '映射预览',
      width: '600px',
      content: <MapResult resultObj={resultObj} />,
      maskClosable: false,
      isOkBtn: false,
      isCancelBtn: true,
      cancel: () => {
        Modal.close();
      },
    });
  };

  const getFormatObject = (data) => {
    const result = {};
    data.forEach((item) => {
      const itemList = item.split('.');
      itemList.reduce((prev, next, index) => {
        if (!prev[next]) prev[next] = {};
        if (index === itemList.length - 1) prev[next] = '';
        return prev[next];
      }, result);
    });
    return result;
  };

  const handleChange = (value, frontId, key) => {
    const temp = [...data];
    const index = temp.findIndex((item) => item.frontId === frontId);
    temp[index][key] = value;
    setData(temp);
  };

  const handleMap = (record) => {
    const { thirdPath, innerPath, frontId } = record;
    if (!thirdPath || !innerPath) return message.warning('请填写key值!');
    Modal.open({
      title: '码值映射设置',
      width: '1000px',
      content: <CodeMap record={record} ref={codeMapRef} />,
      maskClosable: false,
      ok: () => {
        const temp = [...data];
        const index = temp.findIndex((item) => item.frontId === frontId);
        temp[index]['codeMap'] = codeMapRef.current.getData();
        setData(temp);
        Modal.close();
      },
    });
  };

  const handleDelete = (frontId) => {
    const temp = [...data];
    const index = temp.findIndex((item) => item.frontId === frontId);
    temp.splice(index, 1);
    setData(temp);
  };

  const columns = [
    {
      title: '源key',
      dataIndex: 'thirdPath',
      render: (text, { isNew, frontId }) =>
        isNew ? (
          <Input value={text} onChange={(e) => handleChange(e.target.value, frontId, 'thirdPath')} />
        ) : (
          <span>{text}</span>
        ),
    },
    {
      title: '映射key',
      dataIndex: 'innerPath',
      render: (text, { frontId }) => (
        <Input value={text} onChange={(e) => handleChange(e.target.value, frontId, 'innerPath')} />
      ),
    },
    {
      title: '数据类型',
      dataIndex: 'type',
      render: (text, { frontId }) => (
        <Select placeholder='请选择' value={text} onChange={(value) => handleChange(value, frontId, 'type')}>
          {TYPE_OPTIONS.map((item, index) => (
            <Select.Option value={index} key={index}>
              {item}
            </Select.Option>
          ))}
        </Select>
      ),
    },
    {
      title: '返回key(是否)',
      dataIndex: 'isReturning',
      render: (text, { frontId }) => (
        <Select value={text} onChange={(value) => handleChange(value, frontId, 'isReturning')}>
          {['否', '是'].map((item, index) => (
            <Select.Option key={index} value={index}>
              {item}
            </Select.Option>
          ))}
        </Select>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <>
          <Button type='link' onClick={() => handleMap(record)} style={{ marginRight: '20px' }}>
            码值映射
          </Button>
          <Button type='link' onClick={() => handleDelete(record.frontId)}>
            删除
          </Button>
        </>
      ),
    },
  ];

  return (
    <div className='set'>
      <div>
        <Button type='primary' onClick={() => handleParse()}>
          解析
        </Button>
        <span style={{ marginLeft: '20px' }}>用于解析数据源返回结果内容</span>
      </div>
      <Table dataSource={data} columns={columns} rowKey={(_, index) => index} />
      <div style={{ marginTop: '20px' }}>
        <Button onClick={() => handleAdd()} style={{ marginRight: '20px' }}>
          增加
        </Button>
        {!!data.length && <Button onClick={() => handleReview()}>映射预览</Button>}
      </div>
    </div>
  );
});
export default SetUp;
